package com.apes.framework.plugin.esb.processor.connector.yyerp;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.framework.util.MapUtil;
import lombok.Data;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * APP接口调用处理器
 *
 * @author wuq
 * @create 2019-11-26 17:02
 */
@Data
public class ApesAppSignProcessor<T extends SimpleRequest, R> extends AbstractChainProcessor<T, R> {

    private String access_id;
    private String access_key;
    private String method;

    @Override
    protected R doProcess(T request) {
        Map<String, Object> m = request.getMap();
        Map<String, Object> headers;
        JSONObject tempHeader = new JSONObject();
        String action = "POST";
        try {
            if (m.containsKey("headers") && m.containsKey("body")) {
                JSONObject json = new JSONObject(m);
                m = json.getJSONObject("body");
                tempHeader = json.getJSONObject("headers");
                method = tempHeader.getString("method");
                action = tempHeader.get("action") != null &&
                        tempHeader.getString("action").equalsIgnoreCase("GET") ? "GET" : "POST";
            }
            headers = getAPPHeaders(action, method, m.toString().length());

        } catch (Exception e) {
            throw new RuntimeException("获取APP签名报错：" + e.getMessage());
        }
        Map result = MapUtil.mapper("headers", headers, "body", new JSONObject(m), "methodUrl", method);
        if (!tempHeader.isEmpty()) {
            result.put("params", tempHeader);
        }
        return (R) result;
    }

    public Map<String, Object> getAPPHeaders(String action, String sMethod, int length) throws Exception {

        //  按照APP要求，验证的时候去掉第一个 /
        if (sMethod.startsWith("/")) {
            sMethod = sMethod.replaceFirst("/", "");
        }

        String access_key = this.access_key;
        String access_id = this.access_id;
        Calendar calendar = Calendar.getInstance();
        //calendar.add(calendar.HOUR, -8);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT  hjl 2017-05-21
        String time = sdf.format(date);
        String Signature = action + "\\n" + sMethod + "\\n" + length + "\\n" + time;
        //构造密钥: 第一个参数---字节数组(access_key为密钥),第二参数----一个密钥算法的名称

        SecretKeySpec keySpec = new SecretKeySpec(access_key.getBytes("UTF-8"), "HmacSHA1"); //NBsV-7b-ubJuBAPf	NAsV-7b-ubJuBAPg
        //生成一个指定MAC算法的mac对象
        Mac mac = Mac.getInstance("HmacSHA1");
        //用给定密钥初始化 mac 对象
        mac.init(keySpec);
        //使用 HMAC-SHA1 签名方法对对Signature进行签名 ,完成 Mac 操作
        String text = com.alibaba.druid.util.Base64.byteArrayToBase64(mac.doFinal(Signature.getBytes("UTF-8")));
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Authorization", "Jekun "+access_id + ":" + text);//18028603027
        headers.put("Date", time);
        headers.put("Entity-Length", String.valueOf(length));
        headers.put("Signature", Signature);
        headers.put("accessKey", access_key);
        return headers;
    }
}
